<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@ page import="java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.*" %>
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Edit Role</title>
	
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" /> 
	<link rel="stylesheet" type="text/css" href="css/frame.css" />
	
	<style type="text/css">
		input {
			font-size: 20px;
		}
		select {
			font-size: 20px;
		}
		a {
	      text-decoration:none;
	   	}
	</style>
</head>
<body>

<%
	//get session
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
			
	// check session
		if (htp_session == null || htp_session.getAttribute("sUser") == null) {
		    // Forward the control to login.jsp if authentication fails or session expires
		    request.getRequestDispatcher("/login.jsp").forward(request,
		        response);
		}
		if(!"admin".equals(htp_session.getAttribute("sUser"))){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=system_select.jsp"> 	
	<%}
	
	// get parameter	
	String roleId = request.getParameter("roleId");
	String roleNameOld = new String(request.getParameter("roleName").getBytes("ISO8859_1"),"UTF-8");
	String systemId = request.getParameter("systemId");
	String systemNameOld = new String(request.getParameter("systemName").getBytes("ISO8859_1"),"UTF-8");
	String permissionOld = request.getParameter("permissionText");
			
	System.out.println("EDIT roleId "+roleId);////////try////////
	System.out.println("EDIT roleNameOld "+roleNameOld);////////try////////
	System.out.println("EDIT systemId "+systemId);////////try////////
	System.out.println("EDIT systemNameOld "+systemNameOld);////////try////////
	System.out.println("EDIT permissionOld "+permissionOld);////////try////////

	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620" );
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	/* find system in database */
	List<Role> system = new ArrayList<Role>();
	
	try {			   
		ResultSet rs = connect.createStatement().executeQuery("SELECT * " 
				+ " FROM system " + " ORDER BY system_id");
		
		while(rs.next()) {
			Role sys = new Role();
			
			sys.setSystemId(rs.getInt("system_id"));
			sys.setSystemName((rs.getString("system_name")));
			sys.setSystemNameTH((rs.getString("system_name_th")));
			
			system.add(sys);
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}
	
%>

	<div id="page-wrap">
			<div id="inside">
				<table border="0">
					<tr style="font-size:24px">
						<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
							<div id="header_banner-2"></div>
						</td>
						
						<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
							<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
							<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
						</td>
					</tr>
				</table>
				
						<div id="main-content-ac">
        					
							<div class="imageFrame">แก้ไขหน้าที่</div>
							
							<br/><br/><br/><br/><br/><br/>
        					
        					<center>
        					<table width="800" border="0">
        						<form id="form" name="form" method="post" action="">
        						
        							<input type="hidden" id="roleId" name="roleId" value="<%=roleId%>" />
										  		
									<input type="hidden" id="roleName" name="roleName" value="<%=roleNameOld%>" />
						       		<tr style="font-size:24px">
						           	  <td width="400" height="50">
						                	<font size="5"><strong>หน้าที่</strong></font>
						                	<label><font size="5" color="#FF0000">*</font></label>
						                </td>
						                <td width="400" height="50">
						                	<input type="text" name="role" id="role" value="<%=roleNameOld%>" required/>
						                </td>
						            </tr>
						            
						            <input type="hidden" id="systemId" name="systemId" value="<%=systemId%>" />
						            
						            <input type="hidden" id="systemName" name="systemName" value="<%=systemNameOld%>" />
						            <tr style="font-size:24px">
						            	<td width="400" height="50">
						                	<font size="5"><strong>ระบบ</strong></font>
					                        <label><font size="5" color="#FF0000">*</font></label>
						                </td>
						                <td width="400" height="50">
						                	<select name="system">
						                 		<option value="<%=systemId %>"><%=systemNameOld %></option>
<%
												for(Role syst : system) {
													if(Integer.parseInt(systemId) == syst.getSystemId()) {
														
													}
													else {
%>
														<option value="<%=syst.getSystemId()%>" id="<%=syst.getSystemId()%>"><%=syst.getSystemNameTH()%></option>	
<%												
													}
												}
%>
						                    </select>
						                    
						                </td>
						            </tr>
						            
						            <input type="hidden" id="permissionText" name="permissionText" value="<%=permissionOld%>" />
						            <tr style="font-size:24px">
						            	<td width="400" height="50">
						            		<font size="5"><strong>Permission</strong></font>
					                        <label><font size="5" color="#FF0000">*</font></label>
						                </td>
						                <td width="400" height="50">
<%
										char[] permission_char = permissionOld.toCharArray();
										
										if(permission_char[0] == '1') {
%>						                	
					                        <input type="checkbox" name="permission" value="add" id="add" checked/>
<%
										}
										else {
%>
											<input type="checkbox" name="permission" value="add" id="add" />
<%	
										}
%>
					                        <font size="5">เพิ่มข้อมูล</font>
					                      	
					                      	<br>
<%										
										if(permission_char[1] == '1') {
%>						                	
					                        <input type="checkbox" name="permission" value="edit" id="edit" checked/>
<%
										}
										else {
%>
											<input type="checkbox" name="permission" value="edit" id="edit" />
<%	
										}
%>						                    
					                        <font size="5">แก้ไขข้อมูล</font>
					                        
					                        <br>
<%										
										if(permission_char[2] == '1') {
%>						                	
					                        <input type="checkbox" name="permission" value="read" id="read" checked/>
<%
										}
										else {
%>
											<input type="checkbox" name="permission" value="read" id="read" />
<%	
										}
%>					                        
					                        <font size="5">อ่านข้อมูล</font>
					                      	
					                      	<br>
<%										
										if(permission_char[3] == '1') {
%>						                	
					                        <input type="checkbox" name="permission" value="delete" id="delete" checked/>
<%
										}
										else {
%>
											<input type="checkbox" name="permission" value="delete" id="delete" />
<%	
										}
%>
					                        
					                        <font size="5">ลบข้อมูล</font>
						                </td>
						            </tr>
						            
						            <tr>
						            	<td colspan="2">
						            		<label><font size="3" color="#FF0000">หมายเหตุ: * คือ ข้อมูลสำคัญ จำเป็นต้องกรอก</font></label>
						            	</td>
						            </tr>
						            
						             <tr style="font-size:24px">
						            	<td width="400" height="50">
						                	<center><input type="submit" id="save" name="save" class="buttonStyle" value="save"></center>
						                </td>
						       </form>
						                <td width="400" height="50">
						                	<a href="admin_role.jsp"><button class="buttonStyle">cancel</button></a>
						                </td>
						            </tr>
					       </table>
						</center>
						
						<br><br><br>
				
			<div style="clear: both;"></div>
				
			<div id="footer"></div>
			
		</div>		
			<div style="clear: both;"></div>		
   </div>
   
<%
		String checkButton = request.getParameter("save");

		// check save button is pressed
		if("save".equals(checkButton)) {
			// get value from tag
			String roleNew = new String(request.getParameter("role").getBytes("ISO8859_1"),"UTF-8");
			String systemIdNew = request.getParameter("system");
			String permission[] = request.getParameterValues("permission");		
			String permissionNew = "";
			
			// check special character
		   	Pattern regex = Pattern.compile("[$&+,:;=?@#^*<>)(|!%]");
		   	Matcher matcherrole = regex.matcher(roleNew);
		   	if (matcherrole.find()){
			%>
							<script language="javascript"> alert("กรุณาใส่ตัวอักษรหรือตัวเลขเท่านั้น");	</script>
			<%}else{
			
				if(permission == null) {
					System.out.println("null");////////////////////try///////////////////
	%>
					<script type="text/javascript"> alert("กรุณาเลือก permission ก่อนค่ะ");  </script>
	<%				
				}
				else {
					boolean checkAdd = true;
					boolean checkEdit = true;
					boolean checkRead = true;
					boolean checkDelete = true;
					
					// set permission add
					for(int i=0; i<permission.length; i++) {
						if("add".equals(permission[i])) {
							permissionNew = permissionNew + "1";
							checkAdd = false;
						}
					}
					if(checkAdd) {
						permissionNew = permissionNew + "0";
					}
					
					// set permission edit
					for(int i=0; i<permission.length; i++) {
						if("edit".equals(permission[i])) {
							permissionNew = permissionNew + "1";
							checkEdit = false;
						}
					}
					if(checkEdit) {
						permissionNew = permissionNew + "0";
					}
					
					// set permission read
					for(int i=0; i<permission.length; i++) {
						if("read".equals(permission[i])) {
							permissionNew = permissionNew + "1";
							checkRead = false;
						}
					}
					if(checkRead) {
						permissionNew = permissionNew + "0";
					}
					
					// set permission delete
					for(int i=0; i<permission.length; i++) {
						if("delete".equals(permission[i])) {
							permissionNew = permissionNew + "1";
							checkDelete = false;
						}
					}
					if(checkDelete) {
						permissionNew = permissionNew + "0";
					}				
				}
				
				System.out.println("role : "+roleNew);////////////////////try///////////////////
				System.out.println("systemName : "+systemIdNew);////////////////////try///////////////////
				if(permission != null) {
				for(int i=0; i<permission.length; i++)
					System.out.println("permission : "+permission[i]);////////////////////try///////////////////
				}
				System.out.println("permis : "+permissionNew);////////////////////try///////////////////
				
				System.out.println("eq : "+roleNew.equals(roleNameOld));////////////////////try///////////////////
				System.out.println("eq : "+systemIdNew.equals(systemNameOld));////////////////////try///////////////////
				System.out.println("eq : "+permissionNew.equals(permissionOld));////////////////////try///////////////////
				
				if(roleNew.equals(roleNameOld) && systemIdNew.equals(systemId) && permissionNew.equals(permissionOld)) {
	%>
					<script language="javascript"> alert("ข้อมูลไม่มีการเปลี่ยนแปลงค่ะ");	</script>			
	<%				
				}
				else {
					try {			
						// check role name exist
						ResultSet rs = connect.createStatement().executeQuery("SELECT role_name "
													+ " FROM role "
													+ " WHERE role_name='"+roleNew+"'");
						
						rs.last();
						if(rs.getRow() == 1) {
		%>
							<script language="javascript"> alert("หน้าที่นี้มีอยู่ในระบบแล้ว กรุณากรอกใหม่อีกครั้งค่ะ");	</script>
		<%								
						}
						else {
							String sql = "UPDATE `role` SET `role_name`='" + roleNew + "' "
									+ ", permission='" + permissionNew + "' "
									+ ", system_id='" + systemIdNew + "' "
									+ " WHERE role_id=" + roleId;
							connect.createStatement().executeUpdate(sql);
							
							/* Log file */
							String log = "admin edit role";
							Log.writeAdminFile(log);
							Log.writeAdminFile(sql);
							
		%>
							<script language="javascript"> alert("บันทึกข้อมูลสำเร็จ ");	</script>
							<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_role.jsp">
							
		<%
						}
					} catch (SQLException e) {
						e.printStackTrace();
		%>
						<script language="javascript"> alert("มีข้อผิดพลาดเกิดขึ้น กรุณาลองใหม่อีกครั้งค่ะ");	</script>
		<%
					}		
				}
			}
			
		}
		
		connect.close();
%>
</body>
</html>